package lumis.service.chatroom;

import java.util.Collection;
import java.util.Date;

import lumis.collaboration.chat.ChatConversationConfig;
import lumis.collaboration.chat.ChatManagerFactory;
import lumis.collaboration.chat.ChatMessageConfig;
import lumis.collaboration.chat.ChatUserConfig;
import lumis.doui.DouiStringResource;
import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.service.ServiceException;
import lumis.portal.serviceinterface.IServiceInterfaceUrl;
import lumis.portal.serviceinterface.ServiceInterfaceConfig;
import lumis.portal.user.UserConfig;
import lumis.util.IResource;

/**
 * Processes a user request to participate in a chat conversation
 *
 * @version $Revision: 9071 $ $Date: 2008-03-26 11:45:47 -0300 (Wed, 26 Mar 2008) $
 * @since 4.0.6
 */
public class ParticipateProcessActionHandler extends ProcessActionHandler<Source>
{
	protected IResource chatRoomResource = new DouiStringResource();
	
	public ParticipateProcessActionHandler()
	{
		chatRoomResource.addResourcePath("lumis/service/chatroom/strings/strings");
	}
	
	@SuppressWarnings("unchecked")
	public void processAction() throws PortalException
	{
		ChatUserConfig chatUserConfig = null;
		String chatConversationId = (String)this.getParameter("chatConversationId", String.class);
		
		if(chatConversationId == null)
			throw new PortalObjectNotFoundException("STR_CHAT_ROOM_NOT_SPECIFIED", chatRoomResource);
		
		ChatConversationConfig chatConversationConfig = ChatManagerFactory.getChatManager().getConversation(sessionConfig, chatConversationId, transaction);
		
		String userSessionId = sessionConfig.getUserSessionId();
		String userId = sessionConfig.getUserId();
		
		if(userId.equals(UserConfig.USER_GUEST_ID))
		{
			// get the chat user for this session
			try
			{
				chatUserConfig = ChatManagerFactory.getChatManager().getUser(sessionConfig, userId, chatConversationId, userSessionId, transaction);
			}
			catch(PortalObjectNotFoundException e)
			{
				
			}
		}
		else
		{
			// get the chat user for this userId
			try
			{
				chatUserConfig = ChatManagerFactory.getChatManager().getUser(sessionConfig, userId, chatConversationId, null, transaction);
			}
			catch(PortalObjectNotFoundException e)
			{
				
			}
		}
	
		// verify if the candidate to name has been used by another chat user, active or not.  
		Collection<ChatUserConfig> chatUsers = ChatManagerFactory.getChatManager().getUsers(sessionConfig, chatConversationId, transaction);
		String name = getParameter("name", String.class);
		for(ChatUserConfig chatUser: chatUsers)
		{
			if(name.equals(chatUser.getName()) && !chatUser.equals(chatUserConfig))
				throw new PortalException("STR_USER_NAME_IS_BEING_USED;"+ name, getResource());
		}
		
		// add user
		if(chatUserConfig == null)
		{
			chatUserConfig = new ChatUserConfig();
			chatUserConfig.setName(name);
			chatUserConfig.setUserSessionId(sessionConfig.getUserSessionId());
			chatUserConfig.setUserId(userId);
			chatUserConfig.setConversationId(chatConversationId);
			chatUserConfig.setLastAccessDate(new Date());
			ChatManagerFactory.getChatManager().addUser(sessionConfig, chatUserConfig, transaction);
		}
		else
		{
			if(ChatManagerFactory.getChatManager().reachedUserLimit(sessionConfig, chatConversationId, transaction))
			{
				// make sure that the current user is not a moderator
				if(!chatConversationConfig.isModerated() || !chatConversationConfig.getModerator().equals(chatUserConfig.getUserId()))
					throw new PortalException("STR_REACHED_ROOM_LIMIT", chatRoomResource);
			}
			
			chatUserConfig.setName((String)this.getParameter("name", String.class));
			chatUserConfig.setState(ChatUserConfig.CHAT_USER_STATE_ACTIVE);
			chatUserConfig.setLastAccessDate(new Date());
		}

		ChatMessageConfig chatMessageConfig = new ChatMessageConfig();
		chatMessageConfig.setConversationId(chatConversationId);
		chatMessageConfig.setMessage(localize("STR_USER_ENTERED_CONVERSATION;"+chatUserConfig.getName()));
		chatMessageConfig.setSentTime(new Date());
		chatMessageConfig.setType(ChatMessageConfig.TYPE_FRAMEWORK);
		ChatManagerFactory.getChatManager().addMessage(sessionConfig, chatMessageConfig, transaction);
			
		String currentUserId = sessionConfig.getUserId();
		String destinationInterfaceId;
		if(chatConversationConfig.isModerated() && chatConversationConfig.getModerator().equals(currentUserId))
			destinationInterfaceId = "lumis.service.chatroom.moderatorChatRoom";
		else
			destinationInterfaceId = "lumis.service.chatroom.chatRoom";
		
		IServiceInterfaceUrl url = getServiceInterfaceHyperLink(destinationInterfaceId);
		
		if(url == null)
			throw new ServiceException("Destination interface "+destinationInterfaceId+" not found.");
		
		url.setParameter("chatUserId", chatUserConfig.getId());
		url.setParameter("name", chatUserConfig.getName());
		url.setParameter("chatConversationId", chatConversationId);
		String strUrl = url.toString();

		ServiceInterfaceConfig serviceInterfaceConfig = ManagerFactory.getServiceInterfaceManager().getServiceInterfaceConfig(destinationInterfaceId, douiContext.getTransaction());
		String windowProperties = serviceInterfaceConfig.getPopupWindowProperties();

		addResponseParameter(ProcessActionHandler.RESPONSE_TYPE_RUN_JAVASCRIPT, "window.open('"+strUrl+"','_blank', '"+windowProperties+"')");
	}
}
